package frank.zou.test.dbunit.base;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;

public class PropertiesDBUnitHelper extends BasicDBUnitHelper {

	private static final String DBUNIT_CONFIG_HOME = "DBUNIT_CONFIG_HOME";

	private static final String PROPERTIES_SUFFIX = ".properties";

	private static final PropertiesDBUnitHelper instance = new PropertiesDBUnitHelper();

	private Properties props;

	private PropertiesDBUnitHelper() {
		init(DBParameterConstant.FILE_NAME);
	}

	@Override
	protected void init(String fileName) {
		props = new Properties();
		String configPath = getDBUnitConfigHomeValue();
		if (configPath == null || configPath.length() == 0) {
			throw new RuntimeException("The system property \""
					+ DBUNIT_CONFIG_HOME + "\" was not found!");
		}
		File file = new File(configPath + "/" + fileName + PROPERTIES_SUFFIX);
		if (!file.exists()) {
			throw new RuntimeException("Config file \"" + file
					+ "\" not exists!");
		}
		try {
			props.load(new FileInputStream(file));
		} catch (FileNotFoundException e) {
			throw new RuntimeException("Config file \"" + file
					+ "\" not exists!");
		} catch (IOException e) {
			throw new RuntimeException("Load file \"" + file + "\" failed!", e);
		}
	}

	@Override
	protected String getProperty(String name) {
		String value = props.getProperty(name);
		return value;
	}

	/**
	 * 
	 * @return
	 */
	private static String getDBUnitConfigHomeValue() {
		try {
			String dbUnitConfigHome = System.getProperty(DBUNIT_CONFIG_HOME);
			if (dbUnitConfigHome == null) {
				dbUnitConfigHome = "src/test/resources";
				// Properties env = getEnv();
				// dbUnitConfigHome = env.getProperty(DBUNIT_CONFIG_HOME);
				
			}
			return dbUnitConfigHome;
		} catch (Exception e) {
			throw new RuntimeException("Error get system properties values. ",
					e);
		}
	}

	/**
	 * 
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unused")
	private static Properties getEnv() throws Exception {
		Properties prop = new Properties();
		String OS = System.getProperty("os.name").toLowerCase();
		Process p = null;
		if (OS.indexOf("windows") > -1) {
			p = Runtime.getRuntime().exec("cmd /c set"); // if os is windows
		} else {
			p = Runtime.getRuntime().exec("env"); // if os is linux/unix
		}
		BufferedReader br = new BufferedReader(new InputStreamReader(p
				.getInputStream()));
		String line;
		while ((line = br.readLine()) != null) {
			int i = line.indexOf("=");
			if (i > -1) {
				String key = line.substring(0, i);
				String value = line.substring(i + 1);
				prop.setProperty(key, value);
			}
		}
		return prop;
	}

	/**
	 * @return the instance
	 */
	public static PropertiesDBUnitHelper getInstance() {
		return instance;
	}
}
